package org.springblade.modules.aliemail;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class AliEmailService {

	@Resource
	private AliEmailProperties aliEmailProperties;

    public void sendEmail(String toEmail, String subject, String content) {
		SingleSendMailResponse response = null;
		try {
			String accessKeyId = aliEmailProperties.getAccessKeyId();
			String region = aliEmailProperties.getRegion();
			String accessKeySecret = aliEmailProperties.getAccessKeySecret();
			String accountName = aliEmailProperties.getAccountName();
			// 1. 配置客户端
			DefaultProfile profile = DefaultProfile.getProfile(region, accessKeyId, accessKeySecret);
			IAcsClient client = new DefaultAcsClient(profile);

			// 2. 构建请求
			SingleSendMailRequest request = new SingleSendMailRequest();
			request.setAccountName(accountName);
			request.setFromAlias("gs");  // 发信人昵称（可选）
			request.setAddressType(1);  // 1:发信地址，0:系统分配
			request.setTagName("Notification");  // 标签（可选）
			request.setReplyToAddress(true);  // 是否允许回复
			request.setToAddress(toEmail);
			request.setSubject(subject);
			request.setHtmlBody(content);  // 支持HTML内容

			// 3. 发送邮件
			response = client.getAcsResponse(request);
			log.info("邮件发送成功，RequestId: " + response.getRequestId());
		} catch (ClientException e) {
			e.printStackTrace();
		}
    }
}
